﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Persons.Classes;
using Persons.Interfaces;
using System.IO;
using System.Text.RegularExpressions;

namespace Persons.DS
{
    /// <summary>
    /// Класс-наследник интерфейса фабрики для реализации работы с файлами CSV формата
    /// </summary>
    public class DS_CSV : IDS
    {
        private string path;
        public string Path { set { path = value; } }
        private IDS next = null;
        public IDS Next { set { next = value; } }
        public DS_CSV() { }
        public DS_CSV(string _path) { Path = _path; }
        public IDS isReady(string _ext, string _path)
        {
            IDS ret = null;
            if ("csv" == _ext) { ret = this; ret.Path = _path; }
            else if (next != null) { ret = next.isReady(_ext, _path); }
            return ret;
        }

        public void Create(Persona p)
        {
            try
            {
                StreamWriter f = new StreamWriter(path, true);
                f.WriteLine(p.MakeCSVStrFromPersona());
                if (p.Photo != null)
                {
                    f.WriteLine(Encoding.Default.GetChars(p.Photo).Length);
                    f.Write(Encoding.Default.GetChars(p.Photo));
                }
                else
                {
                    f.WriteLine(0);
                }
                f.Close();
            }
            catch(Exception ex)
            {
                throw new SystemException(ex.Message);
            }
        }

        public List<Persona> Read()
        {            
            try
            {
                List<Persona> list = new List<Persona>();
                StreamReader reader = new StreamReader(path);
                string str = reader.ReadLine();
                int length = 0;
                while (str != null)
                {
                    Persona per = Persona.GetPersonaFromCSVStr(str);
                    str = reader.ReadLine();
                    length = Convert.ToInt32(str);
                    byte[] bytes = new byte[length];
                    char[] symbols = new char[length];
                    if (length != 0)
                    {
                        reader.ReadBlock(symbols, 0, length);
                        bytes = Encoding.Default.GetBytes(symbols);
                        per.Photo = bytes;                        
                    }
                    list.Add(per);
                    str = reader.ReadLine();
                }
                reader.Close();
                return list;
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }
        }

        public List<Persona> Read(int ID)
        {
            try
            {
                List<Persona> list = new List<Persona>();
                StreamReader reader = new StreamReader(path);
                string str = reader.ReadLine();
                int length = 0;
                while (str != null)
                {
                    Persona per = Persona.GetPersonaFromCSVStr(str);
                    str = reader.ReadLine();
                    length = Convert.ToInt32(str);
                    byte[] bytes = new byte[length];
                    char[] symbols = new char[length];
                    if (length != 0)
                    {
                        reader.ReadBlock(symbols, 0, length);
                        bytes = Encoding.Default.GetBytes(symbols);
                        per.Photo = bytes;
                    }
                    if (per.ID == ID)
                    {
                        list.Add(per);
                    }
                    str = reader.ReadLine();
                }
                reader.Close();
                return list;
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }
        }

        public void Update(Persona p)
        {
            try
            {
                string path2 = path.Substring(0, path.IndexOf('.')) + "New.csv";
                StreamReader reader = new StreamReader(path);
                string str = reader.ReadLine();
                int length = 0;
                while (str != null)
                {
                    Persona per = Persona.GetPersonaFromCSVStr(str);
                    str = reader.ReadLine();
                    length = Convert.ToInt32(str);
                    byte[] bytes = new byte[length];
                    char[] symbols = new char[length];
                    if (length != 0)
                    {
                        reader.ReadBlock(symbols, 0, length);
                        bytes = Encoding.Default.GetBytes(symbols);
                        per.Photo = bytes;
                    }
                    if (per.ID == p.ID)
                    {
                        per.Fname = p.Fname;
                        per.Lname = p.Lname;
                        per.Age = p.Age;
                        if (p != null)
                        {
                            per.Photo = p.Photo;
                        }
                    }
                    StreamWriter writer = new StreamWriter(path2, true);
                    writer.WriteLine(per.MakeCSVStrFromPersona());
                    if (per.Photo != null)
                    {
                        writer.WriteLine(Encoding.Default.GetChars(per.Photo).Length);
                        writer.Write(Encoding.Default.GetChars(per.Photo));
                    }
                    else
                    {
                        writer.WriteLine(0);
                    }
                    writer.Close();
                    str = reader.ReadLine();
                }
                reader.Close();                
                File.Delete(path);
                File.Move(path2, path);
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }
        }

        public void Delete(int ID)
        {
            try
            {
                string path2 = path.Substring(0, path.IndexOf('.')) + "New.csv";
                StreamReader reader = new StreamReader(path);
                string str = reader.ReadLine();
                int length = 0;
                while (str != null)
                {
                    Persona per = Persona.GetPersonaFromCSVStr(str);
                    str = reader.ReadLine();
                    length = Convert.ToInt32(str);
                    byte[] bytes = new byte[length];
                    char[] symbols = new char[length];
                    if (length != 0)
                    {
                        reader.ReadBlock(symbols, 0, length);
                        bytes = Encoding.Default.GetBytes(symbols);
                        per.Photo = bytes;
                    }
                    if (per.ID != ID)
                    {
                        StreamWriter writer = new StreamWriter(path2, true);
                        writer.WriteLine(per.MakeCSVStrFromPersona());
                        if (per.Photo != null)
                        {
                            writer.WriteLine(Encoding.Default.GetChars(per.Photo).Length);
                            writer.Write(Encoding.Default.GetChars(per.Photo));
                        }
                        else
                        {
                            writer.WriteLine(0);
                        }
                        writer.Close();
                    }
                    str = reader.ReadLine();
                }
                reader.Close();
                File.Delete(path);
                File.Move(path2, path);
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }

        }
    }
}
